package com.example.seed.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.Jmysy.binlog4j.core.BinlogEvent;
import com.gitee.Jmysy.binlog4j.core.IBinlogEventHandler;
import com.gitee.Jmysy.binlog4j.springboot.starter.annotation.BinlogSubscriber;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.event.binlog.BinLog;

/**
 * 数据更改事件处理程序
 *
 * @author admin
 * @date 2023/10/27
 */
@BinlogSubscriber(clientName = "master")
public class DataChangeEventHandler implements IBinlogEventHandler<Object> {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private final BinLog binLog;

    public DataChangeEventHandler(JSqlClient sqlClient) {

        this.binLog = sqlClient.getBinLog();
    }

    @Override
    public void onInsert(BinlogEvent<Object> binlogEvent) {
        String table = binlogEvent.getTable();
        binLog.accept(table, null, MAPPER.valueToTree(binlogEvent.getData()));
    }

    @Override
    public void onUpdate(BinlogEvent<Object> binlogEvent) {
        String table = binlogEvent.getTable();
        String oldDate;
        try {
            oldDate = MAPPER.writeValueAsString(binlogEvent.getOriginalData());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        try {
            binLog.accept(table, MAPPER.readTree(oldDate), MAPPER.valueToTree(binlogEvent.getData()));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onDelete(BinlogEvent<Object> binlogEvent) {
        String table = binlogEvent.getTable();
        binLog.accept(table, MAPPER.valueToTree(binlogEvent.getOriginalData()), null);
    }

    @Override
    public boolean isHandle(String s, String s1) {
        return true;
    }
}
